'''
https://leetcode.cn/problems/construct-quad-tree/description/?envType=study-plan-v2&envId=top-interview-150
'''
from typing import List


# Definition for a QuadTree node.
class Node:
    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
        self.val = val
        self.isLeaf = isLeaf
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight


class Solution:
    def construct(self, grid: List[List[int]]) -> 'Node':
        def isLeaf(a, b, c, d):
            if a == c and b == d: return True
            v = grid[a][b]
            for i in range(a, c + 1):
                for j in range(b, d + 1):
                    if grid[i][j] != v: return False
            return True

        def f(a, b, c, d):
            if a > c or b > d:
                return None
            if isLeaf(a, b, c, d):
                return Node(grid[a][b], True, None, None, None, None)
            midr = (a + c) // 2
            midc = (b + d) // 2
            root = Node(1, False, f(a, b, midr, midc), f(a, midc+1, midr, d),
                        f(midr+1, b, c, midc), f(midr+1, midc+1, c, d))
            return root
        return f(0, 0, len(grid)-1, len(grid)-1)
